<template>
  <el-dialog
    v-model="visible"
    title="版本发布检查"
    width="800px"
    :close-on-click-modal="false"
    :close-on-press-escape="false"
    @close="handleClose"
  >
    <div class="release-check-content">
      <!-- 检查进度 -->
      <div class="check-progress">
        <el-steps :active="currentStep" finish-status="success" align-center>
          <el-step title="基础检查" description="检查版本基本信息" />
          <el-step title="依赖检查" description="检查任务和缺陷状态" />
          <el-step title="质量检查" description="检查代码质量和测试覆盖率" />
          <el-step title="环境检查" description="检查部署环境和配置" />
          <el-step title="准备就绪" description="所有检查通过，可以发布" />
        </el-steps>
      </div>

      <!-- 检查结果 -->
      <div class="check-results">
        <el-collapse v-model="activeCollapse">
          <!-- 基础检查 -->
          <el-collapse-item name="basic" title="基础检查">
            <template #title>
              <div class="check-item-title">
                <el-icon :class="getCheckStatusClass(checkResults.basic.status)">
                  <component :is="getCheckStatusIcon(checkResults.basic.status)" />
                </el-icon>
                <span>基础检查</span>
                <el-tag 
                  :type="getCheckTagType(checkResults.basic.status)" 
                  size="small"
                  class="check-status-tag"
                >
                  {{ getCheckStatusText(checkResults.basic.status) }}
                </el-tag>
              </div>
            </template>
            <div class="check-details">
              <el-row :gutter="16">
                <el-col :span="12" v-for="item in checkResults.basic.items" :key="item.name">
                  <div class="check-detail-item">
                    <el-icon :class="getCheckStatusClass(item.status)">
                      <component :is="getCheckStatusIcon(item.status)" />
                    </el-icon>
                    <span class="item-name">{{ item.name }}</span>
                    <span class="item-value">{{ item.value }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>

          <!-- 依赖检查 -->
          <el-collapse-item name="dependency" title="依赖检查">
            <template #title>
              <div class="check-item-title">
                <el-icon :class="getCheckStatusClass(checkResults.dependency.status)">
                  <component :is="getCheckStatusIcon(checkResults.dependency.status)" />
                </el-icon>
                <span>依赖检查</span>
                <el-tag 
                  :type="getCheckTagType(checkResults.dependency.status)" 
                  size="small"
                  class="check-status-tag"
                >
                  {{ getCheckStatusText(checkResults.dependency.status) }}
                </el-tag>
              </div>
            </template>
            <div class="check-details">
              <el-row :gutter="16">
                <el-col :span="12" v-for="item in checkResults.dependency.items" :key="item.name">
                  <div class="check-detail-item">
                    <el-icon :class="getCheckStatusClass(item.status)">
                      <component :is="getCheckStatusIcon(item.status)" />
                    </el-icon>
                    <span class="item-name">{{ item.name }}</span>
                    <span class="item-value">{{ item.value }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>

          <!-- 质量检查 -->
          <el-collapse-item name="quality" title="质量检查">
            <template #title>
              <div class="check-item-title">
                <el-icon :class="getCheckStatusClass(checkResults.quality.status)">
                  <component :is="getCheckStatusIcon(checkResults.quality.status)" />
                </el-icon>
                <span>质量检查</span>
                <el-tag 
                  :type="getCheckTagType(checkResults.quality.status)" 
                  size="small"
                  class="check-status-tag"
                >
                  {{ getCheckStatusText(checkResults.quality.status) }}
                </el-tag>
              </div>
            </template>
            <div class="check-details">
              <el-row :gutter="16">
                <el-col :span="12" v-for="item in checkResults.quality.items" :key="item.name">
                  <div class="check-detail-item">
                    <el-icon :class="getCheckStatusClass(item.status)">
                      <component :is="getCheckStatusIcon(item.status)" />
                    </el-icon>
                    <span class="item-name">{{ item.name }}</span>
                    <span class="item-value">{{ item.value }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>

          <!-- 环境检查 -->
          <el-collapse-item name="environment" title="环境检查">
            <template #title>
              <div class="check-item-title">
                <el-icon :class="getCheckStatusClass(checkResults.environment.status)">
                  <component :is="getCheckStatusIcon(checkResults.environment.status)" />
                </el-icon>
                <span>环境检查</span>
                <el-tag 
                  :type="getCheckTagType(checkResults.environment.status)" 
                  size="small"
                  class="check-status-tag"
                >
                  {{ getCheckStatusText(checkResults.environment.status) }}
                </el-tag>
              </div>
            </template>
            <div class="check-details">
              <el-row :gutter="16">
                <el-col :span="12" v-for="item in checkResults.environment.items" :key="item.name">
                  <div class="check-detail-item">
                    <el-icon :class="getCheckStatusClass(item.status)">
                      <component :is="getCheckStatusIcon(item.status)" />
                    </el-icon>
                    <span class="item-name">{{ item.name }}</span>
                    <span class="item-value">{{ item.value }}</span>
                  </div>
                </el-col>
              </el-row>
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>

      <!-- 发布配置 -->
      <div v-if="canRelease" class="release-config">
        <el-divider content-position="left">发布配置</el-divider>
        <el-form :model="releaseForm" label-width="120px">
          <el-row :gutter="16">
            <el-col :span="12">
              <el-form-item label="发布类型">
                <el-select v-model="releaseForm.release_type" placeholder="请选择发布类型">
                  <el-option label="主要版本" value="major" />
                  <el-option label="次要版本" value="minor" />
                  <el-option label="补丁版本" value="patch" />
                  <el-option label="热修复" value="hotfix" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="发布环境">
                <el-select v-model="releaseForm.environment" placeholder="请选择发布环境">
                  <el-option label="开发环境" value="development" />
                  <el-option label="测试环境" value="testing" />
                  <el-option label="预发布环境" value="staging" />
                  <el-option label="生产环境" value="production" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item label="发布说明">
            <el-input
              v-model="releaseForm.release_notes"
              type="textarea"
              :rows="3"
              placeholder="请输入发布说明..."
            />
          </el-form-item>
          <el-form-item label="发布选项">
            <el-checkbox-group v-model="releaseForm.options">
              <el-checkbox label="auto_deploy">自动部署</el-checkbox>
              <el-checkbox label="send_notification">发送通知</el-checkbox>
              <el-checkbox label="create_backup">创建备份</el-checkbox>
              <el-checkbox label="run_tests">运行测试</el-checkbox>
            </el-checkbox-group>
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button 
          v-if="!checking && !canRelease" 
          type="primary" 
          @click="startCheck"
          :loading="checking"
        >
          开始检查
        </el-button>
        <el-button 
          v-if="canRelease" 
          type="success" 
          @click="handleRelease"
          :loading="releasing"
        >
          确认发布
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { 
  CircleCheckFilled, 
  CircleCloseFilled, 
  Loading,
  WarningFilled
} from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import type { Version, ReleaseRequest } from '@/api/version'

interface Props {
  modelValue: boolean
  version: Version | null
}

interface Emits {
  (e: 'update:modelValue', value: boolean): void
  (e: 'release', data: ReleaseRequest): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 对话框显示状态
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// 检查状态
const checking = ref(false)
const releasing = ref(false)
const currentStep = ref(0)
const activeCollapse = ref(['basic'])

// 检查结果
const checkResults = ref({
  basic: {
    status: 'pending' as 'pending' | 'success' | 'warning' | 'error',
    items: [
      { name: '版本号', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '版本名称', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '版本描述', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '项目状态', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' }
    ]
  },
  dependency: {
    status: 'pending' as 'pending' | 'success' | 'warning' | 'error',
    items: [
      { name: '关联任务', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '未完成任务', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '关联缺陷', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '未修复缺陷', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' }
    ]
  },
  quality: {
    status: 'pending' as 'pending' | 'success' | 'warning' | 'error',
    items: [
      { name: '代码覆盖率', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '测试通过率', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '代码质量', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '安全扫描', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' }
    ]
  },
  environment: {
    status: 'pending' as 'pending' | 'success' | 'warning' | 'error',
    items: [
      { name: '部署环境', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '配置文件', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '数据库迁移', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' },
      { name: '依赖服务', value: '', status: 'pending' as 'pending' | 'success' | 'warning' | 'error' }
    ]
  }
})

// 发布表单
const releaseForm = ref<ReleaseRequest>({
  release_type: 'minor',
  environment: 'production',
  release_notes: '',
  config: {
    auto_deploy: false,
    send_notification: true,
    create_backup: true,
    run_tests: true
  },
  options: []
})

// 是否可以发布
const canRelease = computed(() => {
  return Object.values(checkResults.value).every(check => 
    check.status === 'success' || check.status === 'warning'
  )
})

// 获取检查状态图标
const getCheckStatusIcon = (status: string) => {
  switch (status) {
    case 'success':
      return CircleCheckFilled
    case 'error':
      return CircleCloseFilled
    case 'warning':
      return WarningFilled
    default:
      return Loading
  }
}

// 获取检查状态样式类
const getCheckStatusClass = (status: string) => {
  return `check-status-${status}`
}

// 获取检查状态标签类型
const getCheckTagType = (status: string) => {
  switch (status) {
    case 'success':
      return 'success'
    case 'error':
      return 'danger'
    case 'warning':
      return 'warning'
    default:
      return 'info'
  }
}

// 获取检查状态文本
const getCheckStatusText = (status: string) => {
  switch (status) {
    case 'success':
      return '通过'
    case 'error':
      return '失败'
    case 'warning':
      return '警告'
    default:
      return '检查中'
  }
}

// 开始检查
const startCheck = async () => {
  if (!props.version) return
  
  checking.value = true
  currentStep.value = 0
  
  try {
    // 模拟检查过程
    await performBasicCheck()
    currentStep.value = 1
    activeCollapse.value = ['dependency']
    
    await performDependencyCheck()
    currentStep.value = 2
    activeCollapse.value = ['quality']
    
    await performQualityCheck()
    currentStep.value = 3
    activeCollapse.value = ['environment']
    
    await performEnvironmentCheck()
    currentStep.value = 4
    
    ElMessage.success('所有检查已完成')
  } catch (error) {
    ElMessage.error('检查过程中出现错误')
  } finally {
    checking.value = false
  }
}

// 执行基础检查
const performBasicCheck = async () => {
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  if (props.version) {
    checkResults.value.basic.items[0].value = props.version.version_number
    checkResults.value.basic.items[0].status = 'success'
    
    checkResults.value.basic.items[1].value = props.version.name
    checkResults.value.basic.items[1].status = 'success'
    
    checkResults.value.basic.items[2].value = props.version.description ? '已填写' : '未填写'
    checkResults.value.basic.items[2].status = props.version.description ? 'success' : 'warning'
    
    checkResults.value.basic.items[3].value = props.version.status
    checkResults.value.basic.items[3].status = props.version.status === 'pre_release' ? 'success' : 'warning'
    
    checkResults.value.basic.status = 'success'
  }
}

// 执行依赖检查
const performDependencyCheck = async () => {
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  if (props.version) {
    checkResults.value.dependency.items[0].value = `${props.version.task_count || 0} 个`
    checkResults.value.dependency.items[0].status = 'success'
    
    const unfinishedTasks = (props.version.task_count || 0) - (props.version.completed_task_count || 0)
    checkResults.value.dependency.items[1].value = `${unfinishedTasks} 个`
    checkResults.value.dependency.items[1].status = unfinishedTasks === 0 ? 'success' : 'warning'
    
    checkResults.value.dependency.items[2].value = `${props.version.defect_count || 0} 个`
    checkResults.value.dependency.items[2].status = 'success'
    
    const unfinishedDefects = (props.version.defect_count || 0) - (props.version.resolved_defect_count || 0)
    checkResults.value.dependency.items[3].value = `${unfinishedDefects} 个`
    checkResults.value.dependency.items[3].status = unfinishedDefects === 0 ? 'success' : 'warning'
    
    checkResults.value.dependency.status = unfinishedTasks === 0 && unfinishedDefects === 0 ? 'success' : 'warning'
  }
}

// 执行质量检查
const performQualityCheck = async () => {
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 模拟质量检查结果
  checkResults.value.quality.items[0].value = '85%'
  checkResults.value.quality.items[0].status = 'success'
  
  checkResults.value.quality.items[1].value = '92%'
  checkResults.value.quality.items[1].status = 'success'
  
  checkResults.value.quality.items[2].value = 'A'
  checkResults.value.quality.items[2].status = 'success'
  
  checkResults.value.quality.items[3].value = '通过'
  checkResults.value.quality.items[3].status = 'success'
  
  checkResults.value.quality.status = 'success'
}

// 执行环境检查
const performEnvironmentCheck = async () => {
  await new Promise(resolve => setTimeout(resolve, 1000))
  
  // 模拟环境检查结果
  checkResults.value.environment.items[0].value = '正常'
  checkResults.value.environment.items[0].status = 'success'
  
  checkResults.value.environment.items[1].value = '已更新'
  checkResults.value.environment.items[1].status = 'success'
  
  checkResults.value.environment.items[2].value = '已准备'
  checkResults.value.environment.items[2].status = 'success'
  
  checkResults.value.environment.items[3].value = '运行正常'
  checkResults.value.environment.items[3].status = 'success'
  
  checkResults.value.environment.status = 'success'
}

// 处理发布
const handleRelease = async () => {
  releasing.value = true
  
  try {
    // 构建发布请求数据
    const releaseData: ReleaseRequest = {
      ...releaseForm.value,
      config: {
        auto_deploy: releaseForm.value.options.includes('auto_deploy'),
        send_notification: releaseForm.value.options.includes('send_notification'),
        create_backup: releaseForm.value.options.includes('create_backup'),
        run_tests: releaseForm.value.options.includes('run_tests')
      }
    }
    
    emit('release', releaseData)
    handleClose()
  } catch (error) {
    ElMessage.error('发布失败')
  } finally {
    releasing.value = false
  }
}

// 关闭对话框
const handleClose = () => {
  visible.value = false
  // 重置状态
  currentStep.value = 0
  activeCollapse.value = ['basic']
  Object.keys(checkResults.value).forEach(key => {
    const check = checkResults.value[key as keyof typeof checkResults.value]
    check.status = 'pending'
    check.items.forEach(item => {
      item.status = 'pending'
      item.value = ''
    })
  })
}
</script>

<style scoped>
.release-check-content {
  max-height: 600px;
  overflow-y: auto;
}

.check-progress {
  margin-bottom: 24px;
}

.check-results {
  margin-bottom: 24px;
}

.check-item-title {
  display: flex;
  align-items: center;
  gap: 8px;
  width: 100%;
}

.check-status-tag {
  margin-left: auto;
}

.check-status-success {
  color: #67c23a;
}

.check-status-error {
  color: #f56c6c;
}

.check-status-warning {
  color: #e6a23c;
}

.check-status-pending {
  color: #909399;
}

.check-details {
  padding: 16px 0;
}

.check-detail-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.check-detail-item:last-child {
  border-bottom: none;
}

.item-name {
  flex: 1;
  color: #606266;
}

.item-value {
  font-weight: 500;
  color: #303133;
}

.release-config {
  margin-top: 24px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>